﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BLToolkit.Data;
using BLToolkit.Data.Linq;
using BLToolkit.Reflection;
using BLToolkit.TypeBuilder;
using Devsoft.DB.Models;

namespace Devsoft.DB.Models.Flat
{
    [Serializable]
    public class ModelWithManager<T, TManager> : BaseModel
        where T : ModelWithManager<T, TManager>
        where TManager : Manager<T>
    {
        #region Model Operations

        #region CreateInstance

        public static T CreateInstance()
        {
            return TypeAccessor.CreateInstanceEx<T>();
        }

        #endregion

        public override void Save()
        {
            InsertOrUpdate();
        }

        public override void Delete()
        {
            Objects.Delete(this as T);
        }

        public override void Remove()
        {
            this.Delete();
        }

        public override void Insert(bool forceInsert = false)
        {
            if (!forceInsert && !IsNew)
            {
                throw new Exception("Already inserted. To force insert, use x.Insert(true)");
            }
            if (IdentityField != null)
            {
                object id = GetDbManager().InsertWithIdentity(this as T);
                UpdateInsertedIdentity(id);    
            }
            else
            {
                Objects.Insert(this as T);
            }
            
        }

        public override bool Update(bool forceUpdate = false)
        {
            if (Objects.Update(this as T))
            {
                return true;
            }
            return false;
        }

        public override void InsertOrUpdate()
        {
            if (IsNew)
            {
                Insert(true);
            }
            else
            {
                Update();
            }
        }

        public override void InsertOrReplace()
        {
            var db = GetDbManager();
            db.InsertOrReplace(this as T);
        }


        #endregion

        #region Table Operations

        public static TManager Objects
        {
            get
            {
                /*
                if (_Objects == null)
                {
                    _Objects = CreateMaganger();
                }
                return _Objects;
                 * */
                return CreateMaganger();
            }
        }

        public static ObjectWriter<T> CreateObjectWriter()
        {
            var t = TypeFactory.GetType(typeof(TManager));
            var manager = (TManager)Activator.CreateInstance(t, DBRouter.Default.GetDB(typeof (T)));
            return new ObjectWriter<T>(manager);
        }

        public static TManager ObjectsWithNewConnection
        {
            get
            {
                var t = TypeFactory.GetType(typeof(TManager));
                var manager = (TManager)Activator.CreateInstance(t, DBRouter.Default.GetDB(typeof(T)));
                return manager;
            }
        }

        public static TManagerEx Use<TManagerEx>() where TManagerEx:TManager
        {
            var t = TypeFactory.GetType(typeof(TManagerEx));
            var manager =  Activator.CreateInstance(t, DataContextFactory.GetScopedDataContext<DbManager>((Type) typeof(T)))  ;
            return (TManagerEx)manager;
        }

        #endregion

        #region Protected Methods

        protected static TManager CreateMaganger()
        {
            //return Activator.CreateInstance(typeof(TManager), DataContextFactory.GetScopedDataContext<DbManager>()) as TManager;
            var t = TypeFactory.GetType(typeof(TManager));
            return Activator.CreateInstance(t, DataContextFactory.GetScopedDataContext<DbManager>(typeof(T))) as TManager;
        }

        protected DbManager GetDbManager()
        {
            return DataContextFactory.GetScopedDataContext<DbManager>(typeof(T));
        }

        #endregion
    }
}
